/**
 *可点击对象计时器. 用于控制按钮重复点击频率.
 */

import * as cc from 'cc'
import { Loger } from '../loger/Loger'

class Clickable {
    protected uuid: string = null
    protected _isOk: boolean = false
    debug: boolean = false

    constructor(uuid: string) {
        this.uuid = uuid
    }

    public set isOk(done: boolean) {
        this._isOk = done
    }

    public get isOk(): boolean {
        if (this.debug && !this._isOk) {
            Loger.warn("按钮点击过快:" + this.uuid)
        }
        return this._isOk
    }
}

/**
 * 计时类点击对象. 最小间隔0.5
 */
class TimerClickable extends Clickable {
    protected st: number = 0
    //最小间隔:0.5s.
    protected clickSpacing: number = 100

    public initClickSpacing(space: number) {
        this.clickSpacing = (space < 0 ? 0.1 : space) * 1000
    }

    public get isOk(): boolean {
        this.checkOk()

        if (this.debug && !this._isOk) {
            Loger.warn("按钮点击过快:" + this.uuid)
        }
        return this._isOk
    }

    private checkOk() {
        if (Date.now() - this.st > this.clickSpacing) {
            this._isOk = true
            this.st = Date.now()
        } else {
            this._isOk = false
        }
    }
}

class ClickableMgr {
    private Clickables = {};
    private defaultClickable = new Clickable("undefined");
    private _debugable = true

    public set debugable(d: boolean) {
        this._debugable = d
    }

    private _get(uuid, timer?: number): Clickable {
        if (!uuid) {
            return this.defaultClickable
        }
        let clickable = this.Clickables[uuid]
        if (!clickable) {
            if (timer) {
                clickable = new TimerClickable(uuid)
                clickable.initClickSpacing(timer)
            } else {
                clickable = new Clickable(uuid)
            }
            this.Clickables[uuid] = clickable
        }
        clickable.debug = this._debugable
        return clickable
    }

    public get(event: cc.EventTouch, timer?: number): Clickable {
        let uuid = null, clickable = null
        if (event.target instanceof cc.Node) {
            uuid = event.target.uuid
        }
        return this._get(uuid, timer)
    }

    //获取计时器类点击对象.
    public getT(event: cc.EventTouch): Clickable {
        return this.get(event, 0.1)
    }

    //直接获取相应节点的点击对象.
    public getN(node: cc.Node, timer?: number): Clickable {
        return this._get(node.uuid, timer)
    }
}

//导出一个简易的常量.
export const C = new ClickableMgr()